<template>
  <a-card :bordered="false" class="card-area">
    <div>
      <div class="operator">
        <a-button v-hasPermission="['report:add']" type="primary" ghost @click="add">新增</a-button>
        <a-dropdown v-hasPermission="['report:export']">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exportExcel">导出Excel</a-menu-item>
          </a-menu>
          <a-button>
            更多操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.reportId"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :scroll="{ x: 900 }"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               @change="handleTableChange">
        <template slot="operation" slot-scope="text, record">
          &nbsp;
          <a-icon v-hasPermission="['report:view']" type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
        </template>
      </a-table>
    </div>
    <!-- 检查报表信息查看 -->
    <report-info
      @close="handleReportInfoClose"
      :reportInfoVisiable="reportInfo.visiable"
      :reportInfoData="reportInfo.data">
    </report-info>
    <!-- 新增检查报表 -->
    <report-add
      @success="handleReportAddSuccess"
      @close="handleReportAddClose"
      :reportAddVisiable="reportAddVisiable">
    </report-add>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import ReportAdd from './ReportAdd'
import ReportInfo from './ReportInfo'

export default {
  name: 'Report',
  components: {ReportAdd, ReportInfo, RangeDate},
  data () {
    return {
      advanced: false,
      dataSource: [],
      selectedRowKeys: [],
      queryParams: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      reportAddVisiable: false,
      recordAddVisiable: false,
      reportInfo: {
        visiable: false,
        data: {}
      },
      unitData: []
    }
  },
  computed: {
    columns () {
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      return [{
        title: '报表编号',
        dataIndex: 'reportId',
        sorter: true
      }, {
        title: '检查时间',
        dataIndex: 'createTime',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order
      },{
        title: '检查机构',
        dataIndex: 'officeName'
      }, {
        title: '检查形式',
        dataIndex: 'reportType',
        customRender: (text, row, index) => {
          switch (text) {
            case '1':
              return '例行检查'
            case '2':
              return '突击检查'
            case '3':
              return '特殊日期检查'
            default:
              return text
          }
        }
      }, {
        title: '检查人姓名',
        dataIndex: 'reportPerson'
      },{
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' },
        fixed: 'right',
        width: 120
      }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
      if (!this.advanced) {
        this.queryParams.createTimeFrom = ''
        this.queryParams.createTimeTo = ''
      }
    },
    handleReportAddClose () {
      this.reportAddVisiable = false
    },
    handleReportAddSuccess () {
      this.reportAddVisiable = false
      this.fetch()
    },
    add () {
      this.reportAddVisiable = true
    },
    view (record) {
      this.reportInfo.data = record
      this.reportInfo.visiable = true
    },
    handleReportInfoClose () {
      this.reportInfo.visiable = false
    },
    handleDateChange (value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    exportExcel () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      let user = this.$db.get("USER")
      let company = this.$db.get("COMPANY")
      this.queryParams.companyId = company.value
      this.queryParams.officeId = user.officeId==undefined ? null : user.officeId
      this.queryParams.reportSelf = user.officeId==undefined ? '1' : '0';
      this.$export('report/excel', {
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      // 清空时间选择
      this.$refs.createTime.reset()
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      let user = this.$db.get("USER")
      let company = this.$db.get("COMPANY")
      params.companyId = company.value
      params.officeId = user.officeId == undefined ? null : user.officeId
      params.reportSelf = user.officeId==undefined ? '1' : '0';
      this.loading = true
      this.$get('report', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.pagination = pagination
        this.loading = false
        this.dataSource = data.rows
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
